package com.hanqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanqi.dao.SysMenuFuncMapper;
import com.hanqi.dao.SysUserMapper;
import com.hanqi.entity.SysFuncs;
import com.hanqi.entity.SysMenuFunc;
import com.hanqi.entity.SysUser;
import com.hanqi.service.SysMenuFuncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zjk
 * @since 2019-04-27
 */
@Service
public class SysMenuFuncServiceImpl extends ServiceImpl<SysMenuFuncMapper, SysMenuFunc> implements SysMenuFuncService {

    @Autowired
    protected SysUserMapper sysUserMapper;

    @Override
    public List<String> listFuncPermissionsByUserId(String userId) {
        List<String> permissionList;
        SysUser user = sysUserMapper.selectById(userId);
        if (user.getUserType().equals(1)) { // 超级管理员
            permissionList = baseMapper.listAllPermissions();
        } else {
            permissionList = baseMapper.listFuncPermissionsByUserId(userId);
        }

        if (permissionList != null && !permissionList.isEmpty()) {
            return permissionList;
        }
        return new ArrayList<>();
    }

    @Override
    public List<SysFuncs> ListByMenuId(String menuId) {
        return baseMapper.ListByMenuId(menuId);
    }

    @Override
    public boolean updateMenuCodeById(String menuId, String menuCode) {
        QueryWrapper<SysMenuFunc> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("menu_id", menuId);
        List<SysMenuFunc> list = list(queryWrapper);
        if (list != null && list.size() > 0) {
            for (SysMenuFunc menuFunc : list) {
                String permission = menuFunc.getPermissions();
                String newPermission = menuCode + permission.substring(permission.indexOf(":"));
                menuFunc.setPermissions(newPermission);
                updateById(menuFunc);
            }
        }
        return true;
    }
}
